<template>
  <div class="order-container">
    <!-- 头部状态提示 -->
    <div class="status-header">
      <h2>{{ statusText }}订单</h2>
      <div class="statistics">共 {{ orders.length }} 个订单</div>
    </div>

    <!-- 加载状态 -->
    <div v-if="loading" class="loading-wrapper">
      <el-icon class="is-loading" :size="40"><Loading /></el-icon>
      <p>正在加载订单数据...</p>
    </div>

    <!-- 错误状态 -->
    <div v-else-if="error" class="error-wrapper">
      <el-result icon="error" title="加载失败" :sub-title="errorMessage" />
    </div>

    <!-- 订单列表 -->
    <div v-else class="order-list">
      <div v-if="orders.length === 0" class="empty">
        <el-empty description="暂无相关订单" />
      </div>

      <div v-else v-for="order in orders" :key="order.orderId" class="order-card">
        <!-- 订单头部 -->
        <div class="card-header">
          <div class="order-info">
            <span class="order-number">订单号：{{ order.orderNumber }}</span>
            <span class="order-date">{{ formatDate(order.createdAt) }}</span>
          </div>
          <el-tag :type="statusTagType(order.status)" effect="dark">
            {{ statusMap[order.status] }}
          </el-tag>
          <el-tag 
          style="margin-left: -500px;"
          v-if="order.status === 4 " 
            :type="order.evaState === 1 ? 'success' : 'warning'"
            effect="plain"
            class="evaluation-tag"
          >
            {{ order.evaState === 1 ? '已评价' : '未评价' }}
          </el-tag>

          <el-tag
              v-if="[1,2,3].includes(order.afterSalesFlag)"
              :type="{
                1: 'warning',
                2: 'success',
                3: 'danger'
              }[order.afterSalesFlag]"
              effect="plain"
              class="status-tag"
              style="margin-left: -500px;"  
            >
              {{ 
                { 
                  1: '售后申请中',
                  2: '售后申请通过',
                  3: '售后申请失败'
                }[order.afterSalesFlag] 
              }}
            </el-tag>
        </div>

        <!-- 商品信息 -->
        <div class="product-info">
          <el-image 
            :src="'http://localhost:8092' + order.images" 
            fit="cover" 
            class="product-image"
          >
            <template #error>
              <div class="image-error">图片加载失败</div>
            </template>
          </el-image>
          <div class="product-detail">
            <h3 class="product-name">{{ order.productName }}</h3>
            <div class="price-info">
              <span class="label">单价：</span>
              <span class="value">¥{{ order.price }}</span>
            </div>
            <div class="quantity-info">
              <span class="label">数量：</span>
              <span class="value">x{{ order.quantity }}</span>
            </div>
          </div>
        </div>

        <!-- 订单操作 -->
        <div class="order-actions">
          <div class="total-price">
            总价：<span class="price">¥{{ order.totalAmount }}</span>
          </div>
          <div class="action-buttons">
            <el-button 
              type="primary"
              @click="showOrderDetails(order)"
              class="detail-btn"
            >
              <el-icon><Document /></el-icon> 订单详情
            </el-button>
            <el-button 
              v-if="order.status === 3" 
              type="success" 
              @click="confirmReceipt(order)"
            >
              <el-icon><CircleCheck /></el-icon> 确认收货
            </el-button>

           <el-button 
  v-if="order.status === 4 && [0, null].includes(order.evaState)"
  type="primary" 
  @click="goToReview(order)"
>
  <el-icon><Edit /></el-icon> 去评价
</el-button>

            <el-button  
             v-if="order.status !==5 && ![1,2,3].includes(order.afterSalesFlag)"
              type="warning" 
              @click="applyAfterSales(order)"
            >
              <el-icon><Service /></el-icon> 申请售后
            </el-button>

            <el-button 
              type="info" 
              @click="contactSeller(order)"
            >
              <el-icon><ChatDotRound /></el-icon> 联系卖家
            </el-button>
          </div>
        </div>
      </div>
    </div>
  </div>
  <el-dialog
    v-model="reviewDialogVisible"
    title="商品评价"
    width="40%"
    class="review-dialog"
    :close-on-click-modal="false"
  >
    <div class="review-content">
      <div class="product-info">
        <el-image 
          :src="'http://localhost:8092' + currentOrder?.images" 
          fit="cover"
          class="preview-image"
        />
        <div class="product-meta">
          <h4>{{ currentOrder?.productName }}</h4>
          <p>订单号：{{ currentOrder?.orderNumber }}</p>
        </div>
      </div>

      <div class="rating-section">
        <span class="rating-label">商品评分：</span>
        <el-rate
          v-model="reviewForm.stars"
          :colors="['#99A9BF', '#F7BA2A', '#FF9900']"
          void-color="#EFF2F7"
          allow-half
          show-score
          score-template="{value} 分"
        />
      </div>
      
      <el-input
        v-model="reviewForm.evaluation"
        type="textarea"
        :rows="5"
        placeholder="请描述您的真实体验（10-200字）"
        resize="none"
        class="comment-input"
        maxlength="200"
        show-word-limit
      />
    </div>
    
    <template #footer>
      <el-button @click="reviewDialogVisible = false">取 消</el-button>
      <el-button 
        type="primary"
        :loading="submitting"
        @click="submitReview"
        class="submit-btn"
      >
        提交评价
      </el-button>
    </template>
  </el-dialog>
  
<!-- 申请售后弹窗 -->
  <el-dialog
    v-model="afterSalesDialogVisible"
    title="申请售后"
    width="500px"
    class="after-sales-dialog"
  >
    <el-form :model="afterSalesForm">
      <el-form-item label="售后类型" required>
        <el-radio-group v-model="afterSalesForm.afterSalesType">
          <el-radio 
            :label="1" 
            :disabled="currentOrderForAfterSales?.status !== 2"
          >仅退款</el-radio>
          <el-radio 
            :label="2" 
            :disabled="currentOrderForAfterSales?.status === 2"
          >退货退款</el-radio>
        </el-radio-group>
      </el-form-item>
      <el-form-item label="申请原因" required>
        <el-input
          v-model="afterSalesForm.reason"
          type="textarea"
          :rows="4"
          placeholder="请详细描述您的问题（50-200字）"
          maxlength="200"
          show-word-limit
        />
      </el-form-item>
    </el-form>
    
    <template #footer>
      <el-button @click="afterSalesDialogVisible = false">取消</el-button>
      <el-button 
        type="primary"
        :loading="submittingAfterSales"
        @click="submitAfterSales"
      >
        提交申请
      </el-button>
    </template>
  </el-dialog>
</template>

<script setup>
import { ref, computed, onMounted ,reactive } from 'vue'
import { useRoute, useRouter } from 'vue-router'
import axios from 'axios'
import { 
  Loading, 
  CircleCheck,
  Edit,
  Service,
  ChatDotRound,
  Document
} from '@element-plus/icons-vue'
import { ElMessageBox, ElMessage } from 'element-plus'
import { after } from 'lodash'

const route = useRoute()
const router = useRouter()
const reviewDialogVisible = ref(false)
const submitting = ref(false)
const currentOrder = ref(null)
const reviewForm = reactive({
  orderId: null,
  stars: 5,
  evaluation: ''
})
// 状态映射
const statusMap = {
  1: '待付款',
  2: '已付款',
  3: '已发货',
  4: '已完成',
  5: '已取消'
}

// 响应式数据
const loading = ref(true)
const error = ref(false)
const errorMessage = ref('')
const orders = ref([])
const userInfo = ref(null)
//售后响应式数据
const afterSalesDialogVisible = ref(false)
const submittingAfterSales = ref(false)
const currentOrderForAfterSales = ref(null)
const afterSalesForm = reactive({
  orderId: null,
  afterSalesFlag:null,
  afterSalesType: null,
  reason: ''
})
// 计算属性
const statusText = computed(() => {
  const status = parseInt(route.query.status)
  return statusMap[status] || '全部'
})

// 标签样式映射
const statusTagType = (status) => {
  const typeMap = {
    1: 'warning',
    2: '',
    3: 'success',
    4: 'info',
    5: 'danger'
  }
  return typeMap[status] || 'info'
}

// 方法
const formatDate = (timestamp) => {
  if (!timestamp) return ''
  const date = new Date(timestamp)
  return date.toLocaleDateString('zh-CN', {
    year: 'numeric',
    month: '2-digit',
    day: '2-digit',
    hour: '2-digit',
    minute: '2-digit'
  })
}

const showOrderDetails = (order) => {
  const routeData = router.resolve({
    path: '/orderDetail',
    query: {
      orderId: order.orderId
    }
  })
  window.open(routeData.href, '_blank')
}

const confirmReceipt = async (order) => {
  try {
    await ElMessageBox.confirm(
      '请确认您已收到商品且无损坏',
      '确认收到货了吗？',
      {
        confirmButtonText: '确认收货',
        cancelButtonText: '取消',
        type: 'warning',
        center: true,
      }
    )

    const response = await axios.put('http://localhost:8092/order/confirmReceipt', null, {
      params: {
        orderId: order.orderId
      }
    })

    if (response.data.code === 200) {
      ElMessage.success({
        message: '收货确认成功！',
        duration: 3000,
        showClose: true,
      })
      await fetchOrders()
    } else {
      ElMessage.error(response.data.msg || '操作失败')
    }
    
  } catch (error) {
    if (error !== 'cancel') {
      ElMessage.error(error.response?.data?.msg || '操作失败，请重试')
    }
  }
}

const goToReview = (order) => {
  currentOrder.value = order
  reviewForm.orderId = order.orderId
  reviewForm.stars = order.stars || 5
  reviewForm.evaluation = order.evaluation || ''
  reviewDialogVisible.value = true
}
const submitReview = async () => {
  if (!validateForm()) return
  
  submitting.value = true
  try {
    const response = await axios.put('http://localhost:8092/order/submitReview', {
      orderId: reviewForm.orderId,
      evaluation: reviewForm.evaluation,
      stars: reviewForm.stars
    })

    if (response.data.code === 200) {
      ElMessage.success('评价提交成功！')
      await fetchOrders()
      reviewDialogVisible.value = false
    }
  } catch (error) {
    ElMessage.error(error.response?.data?.msg || '提交失败')
  } finally {
    submitting.value = false
  }
}

const validateForm = () => {
  if (reviewForm.stars < 1) {
    ElMessage.warning('请为商品评分')
    return false
  }
  if (reviewForm.evaluation.trim().length < 10) {
    ElMessage.warning('评价内容至少需要10个字')
    return false
  }
  return true
}
const applyAfterSales = (order) => {
  currentOrderForAfterSales.value = order
  afterSalesForm.orderId = order.orderId
  afterSalesForm.afterSalesType = order.status === 2 ? 1 : null // 默认选中仅退款
  afterSalesForm.reason = ''
  afterSalesDialogVisible.value = true,
  afterSalesForm.afterSalesFlag = 1
}

// 新增提交方法
const submitAfterSales = async () => {
  if (!validateAfterSalesForm()) return
  
  submittingAfterSales.value = true
  try {
    const response = await axios.post('http://localhost:8092/order/applyAfterSales', {
      orderId: afterSalesForm.orderId,
      afterSalesFlag: afterSalesForm.afterSalesFlag,
      afterSalesType: afterSalesForm.afterSalesType,
      reason: afterSalesForm.reason
    })

    if (response.data.code === 200) {
      ElMessage.success('申请提交成功')
      await fetchOrders()
      afterSalesDialogVisible.value = false
    }
  } catch (error) {
    ElMessage.error(error.response?.data?.msg || '提交失败')
  } finally {
    submittingAfterSales.value = false
  }
}

// 表单验证
const validateAfterSalesForm = () => {
  if (!afterSalesForm.afterSalesType) {
    ElMessage.warning('请选择售后类型')
    return false
  }
  if (afterSalesForm.reason.trim().length < 10) {
    ElMessage.warning('原因描述需要至少10字')
    return false
  }
  return true
}

const fetchSellerDetails = async (userId) => {
  try {
    const response = await axios.get('http://localhost:8092/user/getUserDetailById', {
      params: { userId }
    })
    
    if (response.data.code === 200 && response.data.data.length > 0) {
      const seller = response.data.data[0]
      ElMessageBox.alert(
        `<div class="seller-info">
          <p><el-icon><User /></el-icon> 卖家电话：${seller.phone || '未提供'}</p>
          <p><el-icon><Message /></el-icon> 卖家邮箱：${seller.email || '未提供'}</p>
        </div>`,
        '卖家联系方式',
        {
          dangerouslyUseHTMLString: true,
          customClass: 'seller-contact-dialog',
          confirmButtonText: '关闭'
        }
      )
    } else {
      ElMessage.error('获取卖家信息失败')
    }
  } catch (error) {
    ElMessage.error(error.response?.data?.msg || '获取联系方式失败')
  }
}

// 修改联系卖家方法
const contactSeller = async (order) => {
  try {
    await fetchSellerDetails(order.sellerId)
  } catch (error) {
    console.error('联系卖家失败:', error)
  }
}

// 获取用户信息
const fetchUserInfo = async () => {
  try {
    const token = localStorage.getItem('token')
    if (!token) throw new Error('未登录')
    
    const response = await axios.get('http://localhost:8092/user/getUserDetails', {
      headers: {
        Authorization: `Bearer ${token}`
      }
    })
    
    if (response.data.code === 200) {
      userInfo.value = response.data.data
      localStorage.setItem('userInfo', JSON.stringify(response.data.data))
    }
  } catch (err) {
    console.error('获取用户信息失败:', err)
    router.push('/login')
  }
}

// 获取订单数据
const fetchOrders = async () => {
  try {
    loading.value = true
    error.value = false
    
    if (!userInfo.value?.userId) {
      await fetchUserInfo()
    }

    let apiUrl = 'http://localhost:8092/order/getOrderDetailBystate'
    const params = {
      userId: userInfo.value.userId,
      status: route.query.status || 0
    }

    // 判断是否是全部订单
    if (!route.query.status || parseInt(route.query.status) === 0) {
      apiUrl = 'http://localhost:8092/order/getOrdersByUserId'
    } else {
      params.status = route.query.status
    }

    const response = await axios.get(apiUrl, { params })

    if (response.data.code === 200) {
      orders.value = Array.isArray(response.data.data) 
        ? response.data.data.map(order => ({
            ...order,
            createdAt: new Date(order.createdAt).getTime()
          })) 
        : []
    } else {
      throw new Error(response.data.msg || '数据获取失败')
    }
  } catch (err) {
    error.value = true
    errorMessage.value = err.message
    if (err.message.includes('未登录')) {
      router.push('/login')
    }
  } finally {
    loading.value = false
  }
}

onMounted(async () => {
  try {
    const storedUser = localStorage.getItem('userInfo')
    if (storedUser) {
      userInfo.value = JSON.parse(storedUser)
    }
    await fetchUserInfo()
    await fetchOrders()
  } catch (error) {
    console.error('初始化失败:', error)
  }
})
</script>

<style scoped>
.order-container {
  max-width: 1200px;
  margin: 20px auto;
  padding: 20px;
}

.status-header {
  display: flex;
  align-items: center;
  justify-content: space-between;
  margin-bottom: 30px;
  padding: 20px;
  background: #fff;
  border-radius: 8px;
  box-shadow: 0 2px 12px rgba(0,0,0,0.05);
}

.statistics {
  color: #666;
  font-size: 14px;
}

.order-card {
  margin-bottom: 20px;
  padding: 24px;
  background: #fff;
  border-radius: 12px;
  box-shadow: 0 4px 12px rgba(0,0,0,0.08);
  transition: transform 0.3s ease;
}

.order-card:hover {
  transform: translateY(-2px);
}

.card-header {
  display: flex;
  justify-content: space-between;
  align-items: center;
  margin-bottom: 20px;
  padding-bottom: 16px;
  border-bottom: 1px solid #eee;
  gap: 8px; /* 新增整体间距控制 */
}

.order-number {
  color: #666;
  margin-right: 20px;
}

.order-date {
  color: #999;
  font-size: 14px;
}

.product-info {
  display: flex;
  gap: 20px;
  margin-bottom: 20px;
}

.product-image {
  width: 120px;
  height: 120px;
  border-radius: 8px;
  overflow: hidden;
}

.product-detail {
  flex: 1;
}

.product-name {
  margin: 0 0 12px;
  font-size: 18px;
  color: #333;
}

.price-info, .quantity-info {
  margin: 8px 0;
  color: #666;
}

.order-actions {
  display: flex;
  justify-content: space-between;
  align-items: center;
  padding-top: 16px;
  border-top: 1px solid #eee;
}

.total-price {
  font-size: 16px;
}

.total-price .price {
  color: #e4393c;
  font-size: 20px;
  font-weight: bold;
}

.action-buttons {
  display: flex;
  gap: 12px;
}

.detail-btn {
  background: linear-gradient(45deg, #6b47ff, #8a63ff);
  border-color: #6b47ff;
  color: white;
  margin-right: 12px;
}

.detail-btn:hover {
  background: linear-gradient(45deg, #5a3bd8, #7a52e0);
  border-color: #5a3bd8;
}

.el-button {
  padding: 10px 20px;
  border-radius: 20px;
}

.loading-wrapper {
  text-align: center;
  padding: 40px;
  color: #666;
}

.error-wrapper {
  padding: 40px;
  background: #fff;
  border-radius: 8px;
}

.empty {
  padding: 40px;
  background: #fff;
  border-radius: 8px;
}

.image-error {
  display: flex;
  align-items: center;
  justify-content: center;
  width: 100%;
  height: 100%;
  background: #f5f5f5;
  color: #999;
}
.review-dialog {
  :deep(.el-dialog__header) {
    background: linear-gradient(135deg, #6b47ff 20%, #8a63ff 80%);
    margin: 0;
    
    .el-dialog__title {
      color: white;
      font-weight: 600;
      letter-spacing: 1px;
    }
    
    .el-dialog__headerbtn .el-icon {
      color: rgba(255,255,255,0.9);
    }
  }
}

.product-info {
  display: flex;
  gap: 15px;
  margin-bottom: 25px;
  padding: 15px;
  background: #f8f9fa;
  border-radius: 8px;
  
  .preview-image {
    width: 80px;
    height: 80px;
    border-radius: 6px;
    border: 1px solid #eee;
  }
  
  .product-meta {
    h4 {
      margin: 0 0 6px;
      font-size: 15px;
      color: #303133;
    }
    
    p {
      margin: 0;
      font-size: 12px;
      color: #909399;
    }
  }
}

.rating-section {
  display: flex;
  align-items: center;
  margin-bottom: 20px;
  
  .rating-label {
    font-size: 14px;
    color: #606266;
    margin-right: 15px;
  }
  
  :deep(.el-rate) {
    flex-grow: 1;
    
    .el-rate__item {
      font-size: 28px;
    }
    
    .el-rate__text {
      margin-left: 12px;
      font-size: 14px;
      color: #F7BA2A;
      font-weight: 500;
    }
  }
}

.comment-input {
  :deep(.el-textarea__inner) {
    padding: 12px;
    font-size: 14px;
    border-radius: 8px;
    transition: all 0.3s;
    
    &:focus {
      border-color: #6b47ff;
      box-shadow: 0 2px 8px rgba(107,71,255,0.1);
    }
  }
}

.submit-btn {
  background: linear-gradient(45deg, #6b47ff, #8a63ff);
  border: none;
  color: white;
  padding: 10px 24px;
  
  &:hover {
    background: linear-gradient(45deg, #5a3bd8, #7a52e0);
    opacity: 0.9;
  }
  
  &:active {
    transform: scale(0.98);
  }
}

/* 修改后的状态标签样式 */
.status-tags {
  display: flex;
  gap: 4px;  /* 原8px改为4px */
  align-items: center;
}

.evaluation-tag {
  margin-left: 4px;  /* 原8px改为4px */
}

.after-sales-dialog {
  :deep(.el-dialog__header) {
    background: linear-gradient(135deg, #FF6B6B 20%, #FF8E53 80%);
    margin: 0;
    
    .el-dialog__title {
      color: white;
      font-weight: 600;
    }
    
    .el-dialog__headerbtn .el-icon {
      color: rgba(255,255,255,0.9);
    }
  }
  
  .el-radio-group {
    display: flex;
    flex-direction: column;
    gap: 15px;
    
    .el-radio {
      margin-right: 0;
    }
  }
  
  .el-textarea {
    :deep(.el-textarea__inner) {
      min-height: 100px!important;
    }
  }
}
.seller-contact-dialog {
  .el-message-box__content {
    padding: 20px;
    
    p {
      margin: 15px 0;
      font-size: 16px;
      display: flex;
      align-items: center;
      
      .el-icon {
        margin-right: 8px;
        font-size: 18px;
      }
    }
  }
  
  .el-message-box__btns {
    padding: 15px;
  }
}
</style>